
from content.models import UserRating, UserShopping, Goods


def recommend_goods(user):
    # print('开始')
    # 1. 获取用户评分记录：筛选出评分较高的商品
    rated_goods = UserRating.objects.filter(user=user).select_related('goods')
    # 只筛选出评分大于等于 3 的商品
    rated_goods = rated_goods.filter(rating__gte=3)
    # for i in rated_goods:
    #     print(i,'========')

    # 2. 获取用户购物记录：找到用户曾购买的商品
    bought_goods = UserShopping.objects.filter(user=user).select_related('goods')

    # 3. 获取评分较高的商品对应的类别
    rated_goods_ids = [rating.goods.id for rating in rated_goods]
    rated_goods_categories = Goods.objects.filter(id__in=rated_goods_ids).values_list('category', flat=True).distinct()
    # print(rated_goods_categories, '========')

    # 4. 从同一类别的商品中推荐，避免重复推荐用户已购买的商品
    recommended_goods_1 = Goods.objects.filter(category__in=rated_goods_categories).exclude(id__in=rated_goods_ids)
    # print(recommended_goods_1, '========',len(recommended_goods_1))

    # 5. 从用户购物记录中提取购买商品的类别，进行同类商品推荐
    bought_goods_ids = [shopping.goods.id for shopping in bought_goods]
    bought_goods_categories = Goods.objects.filter(id__in=bought_goods_ids).values_list('category',flat=True).distinct()
    # print(bought_goods_categories, '========')

    # 6. 根据用户购买商品类别，推荐同类别的商品recommended_goods.union( )
    recommended_goods_2 = Goods.objects.filter(category__in=bought_goods_categories).exclude(id__in=rated_goods_ids)

    # print(recommended_goods_2, '========',len(recommended_goods_2))

    # 7. 排除用户已购买的商品，避免推荐重复商品
    # recommended_goods = recommended_goods.exclude(id__in=bought_goods_ids)

    all_recommended_goods = recommended_goods_1.union(recommended_goods_2)
    # print(all_recommended_goods, '========',len(all_recommended_goods))
    # 8. 排序推荐商品（假设商品有一个评分字段）
    recommended_goods = all_recommended_goods.order_by('-rating')  # 根据评分进行排序
    all_ids = [goods.id for goods in recommended_goods]
    # print(len(recommended_goods),recommended_goods, '========')
    # 展示推荐商品的名称和评分，形式为(name,rating)
    recommended_goods_list = [(goods.name, goods.rating) for goods in recommended_goods]
    # print(recommended_goods_list, '========')

    #给前五个打上推荐的标签
    # 获取前 5 条记录的 ID 列表
    to_update_ids = list(Goods.objects.filter(id__in=all_ids).order_by('id')[:5].values_list('id', flat=True))
    # print(to_update_ids, '2========')
    Goods.objects.update(is_recommended=False)
    Goods.objects.filter(id__in=to_update_ids).update(is_recommended=True)

